package org.me;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jivesoftware.smack.AccountManager;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.Roster.SubscriptionMode;
import org.jivesoftware.smack.packet.Authentication;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.StreamError;
import org.jivesoftware.smack.util.StringUtils;
import org.me.utils.Koneksi;
import org.me.utils.MyService;
import org.me.utils.PacketEventDispatcher;
import org.me.utils.PacketListener;

public class Chat extends Activity {
	
	XMPPConnection connection;
	private Handler mHandler = new Handler();
	Koneksi koneksi;
	EditText eusername;
	EditText epassword;
	TextView register;
	CheckBox savepass;
	String username;
	String password;
	String requestfrom;
//	static Handler messageHandler = new Handler();
//	static Runnable Refresh;
//	SharedPreferences pref;
	public static final String PREFS_NAME = "MyPrefsFile";
	private static final String PREF_USERNAME = "username";
	private static final String PREF_PASSWORD = "password";

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.login);
//        try {
//			Koneksi.getInstance().init();
//		} catch (XMPPException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
        
//        pref = PreferenceManager.getDefaultSharedPreferences(this);
        
        Typeface font = Typeface.createFromAsset(getAssets(), "fonts/tt0142m_.ttf");
        TextView textUsername = (TextView) findViewById(R.id.textUser);
        textUsername.setTypeface(font);
        TextView textPassword = (TextView) findViewById(R.id.textPass);
        textPassword.setTypeface(font);
        
        SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);   
    	String name = pref.getString(PREF_USERNAME, null);
    	String pass = pref.getString(PREF_PASSWORD, null);
    	
    	System.out.println("SAVE PASS: "+name+" || "+pass);
        
        savepass = (CheckBox) findViewById(R.id.remember);
        savepass.setTypeface(font);
        
        eusername = (EditText) findViewById(R.id.userid);
    	epassword = (EditText) findViewById(R.id.password);
    	
    	if (name == null || pass == null) {
    	    //Prompt for username and password
    		System.out.println("NULL: "+name+" || "+pass);
    		eusername.setText(name);
	    	epassword.setText(pass);
	    	savepass.setChecked(false);
    	}
    	else {
	    	eusername.setText(name);
	    	epassword.setText(pass);
	    	savepass.setChecked(true);
    	}
    	
//    	if(Koneksi.getInstance().getConnection().isAuthenticated()) {
//    		Toast.makeText(this, "authentication: true", Toast.LENGTH_LONG).show();
//    	}
//    	else {
//    		Toast.makeText(this, "authentiation: false", Toast.LENGTH_LONG).show();
//    	}

        
        Button login = (Button) this.findViewById(R.id.login);
        login.setTypeface(font);
        login.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                mHandler.post(new Runnable() {
                    public void run() {
//            	final ProgressDialog dialog = ProgressDialog.show(view.getContext(), null, 
//        			"Connecting", true);
//    			final Handler handler = new Handler() {
//    			   public void handleMessage(Message msg) {
//    			      dialog.dismiss();
//    			   }
//    			};
//    			
//    			Thread checkUpdate = new Thread() {  
//    				   public void run() {
    				//
    				// YOUR LONG CALCULATION (OR OTHER) GOES HERE
    				//
        	System.out.println("+++++login+++++");
            	username = eusername.getText().toString();
            	password = epassword.getText().toString();
            			
            	ServiceConnection conn = new ServiceConnection() {
            		@Override
            		public void onServiceConnected(ComponentName name, IBinder service) {
            			
            		}

					@Override
					public void onServiceDisconnected(ComponentName name) {
						// TODO Auto-generated method stub
						
					}
            	};
        		
        		try {
					Koneksi.getInstance().init();
					Intent myService = new Intent(Chat.this, MyService.class);
		    		Chat.this.startService(myService);
		    		
//		    		Chat.this.bindService(myService, conn, BIND_AUTO_CREATE);
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(getBaseContext(), "Connection failed", Toast.LENGTH_LONG).show();
				}

            	
            	try {
//                    		Koneksi.getInstance().init();
					Koneksi.getInstance().performLogin(username, password);
			        Koneksi.getInstance().setStatus(true, "");
			        Koneksi.getInstance().getConnection().getRoster().setSubscriptionMode(SubscriptionMode.manual);
//					Koneksi.getInstance().chattingManager();
//					Koneksi.getInstance().precenseSubscription();
			        
			        
					if (savepass.isChecked()) {
    					getSharedPreferences(Chat.PREFS_NAME,MODE_PRIVATE)
    	    	        .edit()
    	    	        .putString(Chat.PREF_USERNAME, username)
    	    	        .putString(Chat.PREF_PASSWORD, password)
    	    	        .commit();
	        		}
	        		else {
	        			getSharedPreferences(Chat.PREFS_NAME,MODE_PRIVATE)
		    	        .edit()
		    	        .putString(Chat.PREF_USERNAME, null)
		    	        .putString(Chat.PREF_PASSWORD, null)
		    	        .commit();
	        		}
					
					Intent myIntent = new Intent(getBaseContext(), TabActivity.class);
					startActivity(myIntent);
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(getBaseContext(), "Sign In failed", Toast.LENGTH_LONG).show();
					Koneksi.getInstance().getConnection().disconnect();
				}
				
				
//				handler.sendEmptyMessage(0);
//    				      }
//    				   };
//    				checkUpdate.start();
                    }
                });
            }
        });
        
        
        

        
        
        register = (TextView) findViewById(R.id.register);
        register.setTypeface(font);
        register.setText(Html.fromHtml("<a href=\"http://www.google.com\">Register</a>"));
        register.setMovementMethod(LinkMovementMethod.getInstance());
    }

}


